<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
 * Generic controller for entity class, CI AR.
 * @author hmQuan
 *
 */
class Users extends MY_Controller {

	//contructor class : call contructor of parent
	function __construct() {
		parent::__construct();
		$this->load->model('t_user');
	}

	public function index(){
		$this->load->view('welcome_message');
		// $this->login();
	}

	/**
	 * user login
	 * @return integer : 1|0
	 */
	public function login(){

		//get data post
		$post_data = $this->input->post();
		//check value post if !=null continue else return false
		$post_data = parent::check_post_value($post_data);
		//decode json
		// $post_data = json_decode($post_data[DATA], true);

		$data =array();
		$log = array();
		//check database
		// token gcm
		$gcm_regid = $post_data[GCM_REGID];

		// user_id
		if(isset($post_data[USER_NAME]) && !empty($post_data[USER_NAME])){
			$data[USER_NAME] = $post_data[USER_NAME];
		}else{
			$log[USER_NAME] = INVALID;
		}

		// password 
		if(isset($post_data[USER_PASSWORD]) && !empty($post_data[USER_PASSWORD])){
			$data[USER_PASSWORD] = md5($post_data[USER_PASSWORD]);
		}else{
			$log[USER_PASSWORD] = INVALID;
		}

		if($log != null){
			parent::print_result( $log,FAILVALUE);
			exit();
		}

		// get infor from database
		$query = $this->t_user->get_data_by_property($data);
		// var_dump($query);exit();
		// login success
		if($query != null){
			// unset : password, resetpassword, secretquestion
			unset($query[0][USER_PASSWORD]);
			unset($query[0][USER_RESET_PASSWORD]);	
			unset($query[0][USER_SECRET_QUESTION]);
			//return to client
			parent::print_result($query[0], SUCCESS_VALUE);
			//update login table
			// update table login
			$update = array(GCM_ACTIVE => ISACTIVITY, USER_ID => $query[0][USER_ID]);
			$where = array(GCM_REGID => $gcm_regid);
			$this->gcmmodel->update_infor_gcm_by_property($update, $where);
			require_once('gcmusers.php');
			$gcmusers = new GCMUsers();
			$gcmusers->send_notification_a_devices_android($gcm_regid, NICEDAY);	

			// email
			$email_config = Array(
	            'protocol'  => 'smtp',
	            'smtp_host' => 'ssl://smtp.googlemail.com',
	            'smtp_port' => '465',
	            'smtp_user' => 'vietdreamtech@gmail.com',
	            'smtp_pass' => '@h4ck3r#',
	            'mailtype'  => 'html',
	            'starttls'  => true,
	            'newline'   => "\r\n"
	        );

	        $this->load->library('email', $email_config);

	        $this->email->from('vietdreamtech@gmail.com', 'invoice');
	        $this->email->to('hoangminhquan90@gmail.com');
	        $this->email->subject('Invoice');
	        $this->email->message('Test');

	        $this->email->send();
		}else{
			//failed
			$log[USER_NAME] = INVALID;
			$log[USER_PASSWORD] = INVALID;
			parent::print_result($log, FAILVALUE);
		}
		exit();
	}

	/**
	 * register user
	 */
	public function register($getInfo = 0){

		$post_data = $this->input->post();

		$post_data = parent::check_post_value($post_data);
		
		$data = array();
		$log = array();
		// check fields register
		// token
		$gcm_regid = $post_data[GCM_REGID];

		// check gcm id
		$this->load->model(T_GCMMODEL);
		$count_gcm = $this->gcmmodel->countRegIdAlreadyExist($gcm_regid);
		if($count_gcm == 0){
			$log[GCM_REGID] = -2;
			// parent::print_result(array(GCM_REGID => -2), FAILVALUE);
			// exit();
		}

		// username
		if(!empty($post_data[USER_NAME]) && isset($post_data[USER_NAME])){
			if(strlen($post_data[USER_NAME]) < 6 || strlen($post_data[USER_NAME]) > MAX_LENGHT_USERNAME){
				$log[USER_NAME] = INVALID;
			}else{
				$data[USER_NAME] = $post_data[USER_NAME];
			}
		}else{
			$log[USER_NAME] = INVALID;
		}

		// password
		if(!empty($post_data[USER_PASSWORD]) && isset($post_data[USER_PASSWORD])){
			if(strlen($post_data[USER_PASSWORD]) < 6 ||strlen($post_data[USER_PASSWORD]) > MAX_LENGHT_USERNAME){
				$log[USER_PASSWORD] = INVALID;
			}else{
				$data[USER_PASSWORD] = md5($post_data[USER_PASSWORD]);
			}
		}else{
			$log[USER_PASSWORD] = INVALID;
		}
		// email
		if(!empty($post_data[USER_EMAIL]) &&isset($post_data[USER_EMAIL])){
			if(!$this->validate_email($post_data[USER_EMAIL])){
				$log[USER_EMAIL] = INVALID;
			}else{
				// check unique email
				$queryUniqueEmail = $this->t_user->get_data_by_property(array(USER_EMAIL => $post_data[USER_EMAIL]));
				if(count($queryUniqueEmail) > 0){
					$log[USER_EMAIL] = EXISTED;
				}else{
					$data[USER_EMAIL] = $post_data[USER_EMAIL];	
				}
			}
		}else{
			$log[USER_EMAIL] =  INVALID;
		}

		// phone number
		if(!empty($post_data[USER_PHONE_NUMBER]) && isset($post_data[USER_PHONE_NUMBER])){
			// check unique phone number
			$queryUniquePhone = $this->t_user->get_data_by_property(array(USER_PHONE_NUMBER => $post_data[USER_PHONE_NUMBER]));
			if(count($queryUniquePhone) > 0){
				$log[USER_PHONE_NUMBER] = EXISTED;
			}else{
				$data[USER_PHONE_NUMBER] = $post_data[USER_PHONE_NUMBER];				
			}
		}else{
			$log[USER_PHONE_NUMBER] = INVALID;
		}

		// secret question
		if(isset($post_data[USER_SECRET_QUESTION])){
			$data[USER_SECRET_QUESTION] = $post_data[USER_SECRET_QUESTION];
		}else{
			$log[USER_SECRET_QUESTION] = INVALID;
		}

		// secret answer
		if(isset($post_data[USER_SECRET_ANSWER])){
			$data[USER_SECRET_ANSWER] = $post_data[USER_SECRET_ANSWER];
		}else{
			$log[USER_SECRET_ANSWER] = INVALID;
		}

		// address and user permission
		$this->load->model('t_userpermission');
		$arrPermission = array();
		$arrPermission[UP_SELLER] = $this->t_userpermission->get_data_by_property(array(UP_TYPE => UP_SELLER));
		$arrPermission[UP_USER] = $this->t_userpermission->get_data_by_property(array(UP_TYPE => UP_USER));
		if(!empty($post_data[USER_ADDRESS]) && isset($post_data[USER_ADDRESS])){
			$data[USER_ADDRESS] = $post_data[USER_ADDRESS];
			$data[USER_PERMISSION_ID] = $arrPermission[UP_SELLER][0][UP_ID];
		}else{
			$data[USER_PERMISSION_ID] = $arrPermission[UP_USER][0][UP_ID];
		}

		if($log != null && count($log) > 0){
			parent::print_result($log, FAILVALUE);
			exit();
		}		
		
		// rate
		$data[USER_RATE] = RATE_DEFAULT;
		// reset password
		$data[USER_RESET_PASSWORD] = RESET_PASSWORD_DEFAULT;

		// insert database
		$user = $this->t_user->set_data($data, 1);

		$user_id = $user[0][USER_ID];

		// update path avatar
		$this->t_user->update_data_by_id(array(USER_AVATAR_PATH => UPLOAD_FOLDER_AVATARS . $user_id . '.' . UPLOAD_EXT_DEFAULT), $user_id);

		// update table login
		$update = array(GCM_ACTIVE => ISACTIVITY, USER_ID => $user_id);
		$where = array(GCM_REGID => $gcm_regid);
		$this->gcmmodel->update_infor_gcm_by_property($update, $where);

		//return result
		// unset : password, resetpassword, secretquestion
		unset($user[0][USER_PASSWORD]);
		unset($user[0][USER_RESET_PASSWORD]);
		unset($user[0][USER_SECRET_QUESTION]);
		unset($user[0][USER_SECRET_ANSWER]);
		//return to client
		parent::print_result($user[0], SUCCESS_VALUE);

		// push notification
		// require_once('gcmusers.php');
		// $gcmusers = new GCMUsers();
		// $gcmusers->send_notification_a_devices_android($gcm_regid, WELCOME);

		// send email
		// $email_user = $user[0][USER_EMAIL];

		// $this->load->model('T_email_template');

		// require_once("parse.php");
		
		// $get_parse_email = new ParserEmailTemplate();

		// $get_parse_email->get_template_welcome(array('template' => 'WELCOME_USER'));

		// $parse_email = $get_parse_email->public_template['template'];

		// $parse_subject = $get_parse_email->public_template['subject'];

		// if (!empty($parse_email) && !empty($parse_subject) )
		// {
		// 	require_once("email.php");
		// 	$sendemail = new Email();

		// 	$arraymail = array('SUBJECT' => $parse_subject, 'TO' => $email_user , 'BODY' => $parse_email );

		// 	// send mail
		// 	if($sendemail->send_mail($arraymail)){
		// 	}
		// }
		exit();
	}

	/**
	 * get user information
	 * @return [type] [description]
	 */
	public function get_user_infor(){
		$post = $this->input->post();
		$post = parent::check_post_value($post);

		if(!isset($post[USER_ID]) || empty($post[USER_ID])){
			parent::print_result(array(USER_ID => INVALID));
			exit();
		}
		if(isset($post['fields']) && !empty($post['fields'])){
			$fields = $post['fields'];
		}else{
			$fields = '*';
		}

		$query = $this->t_user->get_data_by_id($post[USER_ID], $fields);
		parent::print_result($query, SUCCESS_VALUE);
		exit();
	}

	// update infor user
	// public function update_infor_user(){
	// 	$post_data = $this->input->post();
	// 	// check post value
	// 	$post_data = parent::check_post_value($post_data);

	// 	// check user
	// 	// gcm id
	// 	$gcm_regid = $post_data[GCM_REGID];
	// 	// user id
	// 	$user_id = $post_data[USER_ID];
		
	// 	$data = array();

	// 	if(isset($post_data[USER_AVATAR_PATH])){
	// 		$data[USER_AVATAR_PATH] = $post_data[USER_AVATAR_PATH];	
	// 	}
		
	// 	if(isset($post_data[USER_ADDRESS])){
	// 		$data[USER_ADDRESS] = $post_data[USER_ADDRESS];	
	// 	}
		
	// 	if(isset($post_data[USER_RATE])){
	// 		$data[USER_RATE] = $post_data[USER_RATE];	
	// 	}
	// 	var_dump($data);exit();
	// }

	/**
	 * change password user
	 * @return integer
	 */
	public function change_password(){

		$post_data = $this->input->post();
		$post_data = parent::check_post_value($post_data);

		// check user
		// gcm id
		$gcm_regid = $post_data[GCM_REGID];
		// user id
		$user_id = $post_data[USER_ID];

		//get status seesion user
		$usr_gcm = $this->t_user->validation_user_gcm($gcm_regid, $user_id);

		// session of user ended. Return.
		if($usr_gcm == null){
			parent::print_result(array('change_password' => INVALID_USER_VALUE), FAILVALUE);
			exit();			
		}

		if( $usr_gcm[0][GCM_ACTIVE] == null){
			parent::print_result(array('change_password' => USER_SESSION), FAILVALUE);
			exit();
		}

		// var_dump($is_activity);exit();

		$log = array();
		$data = array();
		// confirm post value
		
		if(empty($post_data[USER_PASSWORD]) || !isset($post_data[USER_PASSWORD]) || strlen($post_data[USER_PASSWORD]) <6 || strlen($post_data[USER_PASSWORD]) > MAX_LENGHT_USERNAME){
			$log[USER_PASSWORD] = INVALID;
		}
		if(empty($post_data[USER_NEW_PASSWORD]) || !isset($post_data[USER_NEW_PASSWORD]) || strlen($post_data[USER_NEW_PASSWORD]) <6 || strlen($post_data[USER_NEW_PASSWORD]) > MAX_LENGHT_USERNAME){
			$log[USER_NEW_PASSWORD] = INVALID;
		}

		// if error return
		if($log != null){
			parent::print_result($log, FAILVALUE);
			exit();
		}

		//query
		$result = $this->t_user->update_data_by_property(array(USER_PASSWORD => md5($post_data[USER_NEW_PASSWORD])), array(USER_PASSWORD => md5($post_data[USER_PASSWORD]), USER_ID => $user_id));

		if(count($result) != 0){
			// return success
			parent::print_result(array('change_password' => CHANGE_PASSWORD), SUCCESS_VALUE);

			// update session activity gcm and push notification
			// push notification to clients
			require_once('gcmusers.php');
			$gcmusers = new GCMUsers();
			$arrGcm = $this->t_user->get_all_gcm($user_id);
			$this->load->model(T_GCMMODEL);
			foreach ($arrGcm as $key => $user_gcm) {
				if(strcmp($user_gcm[GCM_REGID], $gcm_regid) != 0){
					$update = array(GCM_ACTIVE => 0);
					$where = array(GCM_REGID => $user_gcm[GCM_REGID], USER_ID => $user_gcm[USER_ID]);
					$this->gcmmodel->update_infor_gcm_by_property($update, $where);
					$gcmusers->send_notification_a_devices_android($user_gcm[GCM_REGID], CHANGE_PASSWORD);
				}
			}
			// send email notification
			// send email contain new password
			// $this->load->model('T_email_template');

			// require_once("parse.php");
			
			// $get_parse_email = new ParserEmailTemplate();
			
			// $get_parse_email->get_template_change_password();

			// $parse_email = $get_parse_email->public_template['template'];

			// $parse_subject = $get_parse_email->public_template['subject'];

			// if (!empty($parse_email) && !empty($parse_subject) )
			// {
			// 	require_once("email.php");

			// 	$sendemail = new Email();

			// 	$arraymail = array('SUBJECT' => $parse_subject, 'TO' => $email_user , 'BODY' => $parse_email );

			// 	// send mail
			// 	if($sendemail->send_mail($arraymail)){
			// 	}
			// }
		}else{
			parent::print_result(array('change_password' => 'No row affected'), FAILVALUE);
		}
		exit();
	}

	/**
	 * restore password for user
	 * @return new password via email register
	 */
	public function reset_password(){
		$post = $this->input->post();
		$post = parent::check_post_value($post);

		$gcm_regid = $post[GCM_REGID];
		$user_id = $post[USER_ID];

		// check rule user
		$validation = $this->t_user->validation_user_gcm($gcm_regid, $user_id);

		if($validation == null || count($validation) == 0){
			parent::print_result(array('reset_password' => INVALID_USER_VALUE), 0);
			exit();
		}

		$email_user = $validation[0][USER_EMAIL];
		// general password
		$random_password = $this->random_password();
		// update new password
		$this->t_user->update_data_by_id(array(USER_PASSWORD => $random_password, USER_RESET_PASSWORD => 1), $user_id);
		//return success
		parent::print_result(array('reset_password' => SUCCESS), SUCCESS_VALUE);

		// push notification to clients
		$arrGcm = $this->t_user->get_all_gcm($user_id);
		$this->load->model(T_GCMMODEL);
		$arr_user_gcm = array();
		foreach ($arrGcm as $key => $user_gcm) {
			if(strcmp($user_gcm[GCM_REGID], $gcm_regid) != 0){
				$arr_user_gcm[] = $user_gcm[GCM_REGID];
			}
		}
		require_once('gcmusers.php');
		$gcmusers = new GCMUsers();
		$gcmusers->send_notification_a_devices_android($arr_user_gcm, CHANGE_PASSWORD);

		// send email contain new password
		$this->load->model('T_email_template');

		require_once("parse.php");
		
		$get_parse_email = new ParserEmailTemplate();

		$data_sendmail = array('NEWPASSWORD' => $random_password);
		
		$get_parse_email->get_template_reset_password($data_sendmail);

		$parse_email = $get_parse_email->public_template['template'];

		$parse_subject = $get_parse_email->public_template['subject'];

		if (!empty($parse_email) && !empty($parse_subject) )
		{
			require_once("email.php");

			$sendemail = new Email();

			$arraymail = array('SUBJECT' => $parse_subject, 'TO' => $email_user , 'BODY' => $parse_email );

			// send mail
			if($sendemail->send_mail($arraymail)){
			}
		}
		exit();
	}

	/**
	 * [random_password description]
	 * @return string [description]
	 * format same : Abc1a5g - Lenght = 9
	 */
	private function random_password()
	{
	   	mt_srand((double) microtime() * 10000); //optional for php 4.2.0 and up.

	   	$charid=strtoupper(md5(uniqid(rand(), true)));

	   	$uuid=substr($charid, 0, 8);

	   	return $uuid;
	}

	private function validate_email($email = '') {
	return preg_match('/^(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){255,})(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){65,}@)((?>(?>(?>((?>(?>(?>\x0D\x0A)?[	 ])+|(?>[	 ]*\x0D\x0A)?[	 ]+)?)(\((?>(?2)(?>[\x01-\x08\x0B\x0C\x0E-\'*-\[\]-\x7F]|\\\[\x00-\x7F]|(?3)))*(?2)\)))+(?2))|(?2))?)([!#-\'*+\/-9=?^-~-]+|"(?>(?2)(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\x7F]))*(?2)")(?>(?1)\.(?1)(?4))*(?1)@(?!(?1)[a-z0-9-]{64,})(?1)(?>([a-z0-9](?>[a-z0-9-]*[a-z0-9])?)(?>(?1)\.(?!(?1)[a-z0-9-]{64,})(?1)(?5)){0,126}|\[(?:(?>IPv6:(?>([a-f0-9]{1,4})(?>:(?6)){7}|(?!(?:.*[a-f0-9][:\]]){7,})((?6)(?>:(?6)){0,5})?::(?7)?))|(?>(?>IPv6:(?>(?6)(?>:(?6)){5}:|(?!(?:.*[a-f0-9]:){5,})(?8)?::(?>((?6)(?>:(?6)){0,3}):)?))?(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(?>\.(?9)){3}))\])(?1)$/isD', $email);
  }

  function do_upload_post()
	{
		$this->load->helper(array('form', 'url'));

		$config['upload_path'] = './uploads/';
		$config['allowed_types'] = 'gif|jpg|png';
		$config['max_size']	= '2000';
		$config['max_width']  = '4000';
		$config['max_height']  = '4000';

		$this->upload->initialize($config);

		if (!$this->upload->do_upload())
		{
			$error = array('error' => $this->upload->display_errors());

			$this->load->view('upload_form', $error);
		}
		else
		{
			$data = array('upload_data' => $this->upload->data());

			$this->load->view('upload_success', $data);
		}
	}
}